package com.gla.giliair.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gla.giliair.dao.CabinInfoDao;
import com.gla.giliair.dao.CustomerDao;
import com.gla.giliair.dao.FlightDao;
import com.gla.giliair.dao.MOrderDao;
import com.gla.giliair.entity.*;
import com.gla.giliair.service.*;
import com.gla.giliair.util.BeanUtil;
import com.gla.giliair.util.MapGenerator;
import com.gla.giliair.util.SnowflakeIdUtil;
import com.gla.giliair.web.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description:
 * @Author: Yingtian qian
 * @Date: 2021/8/24 19:05
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private MOrderDao mOrderDao;

    @Autowired
    private FlightDao flightDao;

    @Autowired
    private CustomerDao customerDao;

    @Autowired
    private CabinInfoDao cabinInfoDao;

    @Autowired
    private FlightService flightService;

    @Autowired
    private CabinInfoService cabinInfoService;

    @Autowired
    private PlanemodelService planemodelService;

    @Autowired
    private DiscountService discountService;

    @Autowired
    private UserService userService;

    @Override
    public MOrder selectOrderById(Long orderId) {
        if (orderId != null) {
            MOrderExample mOrderExample = new MOrderExample();
            mOrderExample.or().andOrderIdEqualTo(orderId).andIsDeletedEqualTo(0);
            List<MOrder> orderList = mOrderDao.selectByExample(mOrderExample);
            if (orderList.isEmpty()) {
                return null;
            }
            return orderList.get(0);
        }
        return null;
    }

    @Override
    public MOrder selectOrderByNumber(String orderNumber) {
        if (StringUtils.hasText(orderNumber)) {
            MOrderExample mOrderExample = new MOrderExample();
            mOrderExample.or().andOrderNumberEqualTo(orderNumber).andIsDeletedEqualTo(0);
            List<MOrder> orderList = mOrderDao.selectByExample(mOrderExample);
            if (orderList.isEmpty()) {
                return null;
            }
            return orderList.get(0);
        }
        return null;
    }

    @Override
    public MOrder selectOrderByIDNumberAndFlightId(String IDNumber, Long flightId) {
        if (StringUtils.hasText(IDNumber) && flightId != null) {
            MOrderExample mOrderExample = new MOrderExample();
            mOrderExample.or().andIdNumberEqualTo(IDNumber).andFlightIdEqualTo(flightId).andIsDeletedEqualTo(0);
            List<MOrder> orderList = mOrderDao.selectByExample(mOrderExample);
            if (orderList.isEmpty()) {
                return null;
            }
            return orderList.get(0);
        }
        return null;
    }

    @Override
    public List<MOrder> selectOrdersByCustomerId(Long customerId) {
        if (customerId != null) {
            MOrderExample mOrderExample = new MOrderExample();
            mOrderExample.setOrderByClause("order_id desc");
            mOrderExample.or().andCustomerIdEqualTo(customerId).andIsDeletedEqualTo(0);
            List<MOrder> orderList = mOrderDao.selectByExample(mOrderExample);
            return orderList;
        }
        return null;
    }

    @Override
    public List<MOrder> selectOrdersByCustomerIdAndStates(Long customerId, List<Integer> stateList) {
        MOrderExample mOrderExample = new MOrderExample();
        mOrderExample.setOrderByClause("order_id desc");
        if (stateList != null) {
            for (Integer state : stateList) {
                if (state == null) {
                    continue;
                }
                mOrderExample.or().andCustomerIdEqualTo(customerId).andOrderStateEqualTo(state).andIsDeletedEqualTo(0);
            }
        } else {
            mOrderExample.or().andCustomerIdEqualTo(customerId).andIsDeletedEqualTo(0);
        }
        List<MOrder> orderList = mOrderDao.selectByExample(mOrderExample);
        return orderList;
    }

    @Override
    public List<MOrder> selectOrdersByStates(List<Integer> stateList, MOrderExample orderBy) {
        if (stateList != null) {
            for (Integer state : stateList) {
                if (state == null) {
                    continue;
                }
                orderBy.or().andOrderStateEqualTo(state).andIsDeletedEqualTo(0);
            }
        } else {
            orderBy.or().andIsDeletedEqualTo(0);
        }
        List<MOrder> orderList = mOrderDao.selectByExample(orderBy);
        return orderList;
    }

    @Override
    public List<MOrder> selectOrdersByIDNumberAndStates(String IDNumber, List<Integer> stateList) {
        MOrderExample mOrderExample = new MOrderExample();
        mOrderExample.setOrderByClause("order_id desc");
        if (stateList != null) {
            for (Integer state : stateList) {
                if (state == null) {
                    continue;
                }
                mOrderExample.or().andIdNumberEqualTo(IDNumber).andOrderStateEqualTo(state).andIsDeletedEqualTo(0);
            }
        } else {
            mOrderExample.or().andIdNumberEqualTo(IDNumber).andIsDeletedEqualTo(0);
        }
        List<MOrder> orderList = mOrderDao.selectByExample(mOrderExample);
        return orderList;
    }

    @Override
    public Map<String, Object> findOrdersByCustomerIdAndStates(Long customerId, List<Integer> stateList, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<MOrder> orderList = null;
        //多余的验证
        if (stateList == null) {
            orderList = selectOrdersByCustomerId(customerId);
        } else {
            orderList = selectOrdersByCustomerIdAndStates(customerId, stateList);
        }
        PageInfo pageInfo = new PageInfo(orderList);

        if (!orderList.isEmpty()) {
            List<OrderVO> orderVOList = BeanUtil.copyList(orderList, OrderVO.class);
            pageInfo.setList(orderVOList);
            return MapGenerator.getResWithData(200, "获取订单列表成功！", pageInfo);
        } else {
            return MapGenerator.getRes(201, "获取结果为空！");
        }
    }

    @Override
    public Map<String, Object> createOrder(MOrder mOrder) {
        Flight flightFromDB = flightService.selectFlightById(mOrder.getFlightId());
        if (flightFromDB == null) {
            return MapGenerator.getRes(511, "航班不存在！");
        }

        MOrder orderFromDB = selectOrderByIDNumberAndFlightId(mOrder.getIdNumber(), mOrder.getFlightId());
        if (orderFromDB != null) {
            if (orderFromDB.getOrderState() >= 0 || orderFromDB.getOrderState() == -5) {
                return MapGenerator.getRes(516, "同一航班每一身份证号只能订一张票！");
            }
        }

        Date nowDate = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(nowDate);
        calendar.add(Calendar.HOUR, 1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sDateStr = sdf.format(calendar.getTime());
        try {
            Date sDate = sdf.parse(sDateStr);
            if (sDate.after(flightFromDB.getLeaveTime())) {
                return MapGenerator.getRes(512, "订票时间截止到起飞前一小时，已超时，请去机场人工办理手续！");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        CabinInfo cabinInfoFromDB = cabinInfoService.selectCabinInfoById(flightFromDB.getCabinInfoId());
        Planemodel planemodelFromDB = planemodelService.selectPlanemodelById(flightFromDB.getPlanemodelId());
        if (planemodelFromDB == null) {
            return MapGenerator.getRes(514, "原飞机机型已被删除！");
        }

        //获取订单原价和所选舱位数量
        BigDecimal originalPrice = new BigDecimal(0);
        Integer seatType = mOrder.getSeatType();
        if (seatType == 0) {
            originalPrice = cabinInfoFromDB.getEconomyClassPrice();
            Integer classUsedTotality = cabinInfoFromDB.getEconomyClassUsedTotality();
            if (classUsedTotality.equals(planemodelFromDB.getEconomyClassTotality())) {
                return MapGenerator.getRes(513, "所选舱位已满！");
            }
            classUsedTotality += 1;
            cabinInfoFromDB.setEconomyClassUsedTotality(classUsedTotality);
        } else if (seatType == 1) {
            originalPrice = cabinInfoFromDB.getBusinessClassPrice();
            Integer classUsedTotality = cabinInfoFromDB.getBusinessClassUsedTotality();
            if (classUsedTotality.equals(planemodelFromDB.getBusinessClassTotality())) {
                return MapGenerator.getRes(513, "所选舱位已满！");
            }
            classUsedTotality += 1;
            cabinInfoFromDB.setBusinessClassUsedTotality(classUsedTotality);
        } else if (seatType == 2) {
            originalPrice = cabinInfoFromDB.getFirstClassPrice();
            Integer classUsedTotality = cabinInfoFromDB.getFirstClassUsedTotality();
            if (classUsedTotality.equals(planemodelFromDB.getFirstClassTotality())) {
                return MapGenerator.getRes(513, "所选舱位已满！");
            }
            classUsedTotality += 1;
            cabinInfoFromDB.setFirstClassUsedTotality(classUsedTotality);
        }
        //修改已使用舱位数量
        if (cabinInfoDao.updateByPrimaryKeySelective(cabinInfoFromDB) <= 0) {
            return MapGenerator.getRes(520, "内部错误！");
        }

        mOrder.setOriginalPrice(originalPrice);

        /*
        mOrder.setFlightNumber(flightFromDB.getFlightNumber());
        mOrder.setLeavePoint(flightFromDB.getLeavePoint());
        mOrder.setArrivePoint(flightFromDB.getArrivePoint());
        mOrder.setLeaveAirport(flightFromDB.getLeaveAirport());
        mOrder.setArriveAirport(flightFromDB.getArriveAirport());
        mOrder.setLeaveTime(flightFromDB.getLeaveTime());
        mOrder.setArriveTime(flightFromDB.getArriveTime());
        mOrder.setFlightDuration(flightFromDB.getFlightDuration());

        mOrder.setCompanyId(flightFromDB.getCompanyId());
        mOrder.setCompanyName(flightFromDB.getCompanyName());
        mOrder.setPlanemodelId(flightFromDB.getPlanemodelId());
        mOrder.setPlanemodelName(flightFromDB.getPlanemodelName());
        */
        //批量拷贝flight冗余字段
        BeanUtil.copyOne(flightFromDB, mOrder);

        //根据身份证号添加生日
        String birthdayStr = mOrder.getIdNumber().substring(6, 14);
        String temp1 = birthdayStr.replaceAll("(.{4})", "$1-");
        String temp2 = temp1.replaceAll("(.{7})", "$1-");
        String dateStr = temp2.substring(0, temp2.length() - 1);
        Date birthday = null;
        sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            birthday = sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
            return MapGenerator.getRes(520, "内部错误！");
        }
        mOrder.setBirthday(birthday);

        //根据生日计算是否享受儿童票折扣
        Date validDate = null;
        calendar = Calendar.getInstance();
        calendar.setTime(birthday);
        calendar.add(Calendar.YEAR, 12);
        String validDateStr = sdf.format(calendar.getTime());
        try {
            validDate = sdf.parse(validDateStr);
            if (validDate.after(nowDate)) {
                mOrder.setDiscountType1(1);
            } else {
                mOrder.setDiscountType1(0);
            }
        } catch (ParseException e) {
            e.printStackTrace();
            return MapGenerator.getRes(520, "内部错误！");
        }

        //计算订单折扣后价格
        Discount discountFromDB = discountService.selectDiscountById(cabinInfoFromDB.getDiscountId());
        if (discountFromDB == null) {
            return MapGenerator.getRes(515, "原折扣幅度信息已被删除！");
        }
        mOrder.setPrice(calculatePrice(originalPrice, discountFromDB, mOrder.getDiscountType1(), mOrder.getDiscountType2()));

        //生成订单编号
        mOrder.setOrderNumber(String.valueOf(SnowflakeIdUtil.getSnowflakeId()));
        //覆盖部分多余的批量拷贝的冗余字段
        mOrder.setCreateTime(nowDate);
        mOrder.setUpdateTime(nowDate);

        if (mOrderDao.insertSelective(mOrder) > 0) {
            //返回结果携带添加的订单模版
            return MapGenerator.getResWithData(200, "生成订单成功！", mOrder);
        }
        return MapGenerator.getRes(520, "内部错误！");
    }

    @Override
    public Map<String, Object> cancelOrder(MOrder mOrder) {
        MOrder mOrderFromDB = selectOrderById(mOrder.getOrderId());
        if (mOrderFromDB == null) {
            return MapGenerator.getRes(500, "订单不存在！");
        }
        if (!mOrder.getCustomerId().equals(mOrderFromDB.getCustomerId())) {
            return MapGenerator.getRes(501, "无权限取消！");
        }
        if (mOrderFromDB.getOrderState() != 0) {
            return MapGenerator.getRes(502, "订单状态不为待支付，不能取消！");
        }

        //修改已使用舱位数量
        CabinInfo cabinInfoFromDB = cabinInfoService.selectCabinInfoByFlightId(mOrderFromDB.getFlightId());
        Integer seatType = mOrderFromDB.getSeatType();
        if (seatType == 0) {
            Integer classUsedTotality = cabinInfoFromDB.getEconomyClassUsedTotality();
            classUsedTotality -= 1;
            if (classUsedTotality < 0) {
                return MapGenerator.getRes(520, "内部错误！");
            }
            cabinInfoFromDB.setEconomyClassUsedTotality(classUsedTotality);
        } else if (seatType == 1) {
            Integer classUsedTotality = cabinInfoFromDB.getBusinessClassUsedTotality();
            classUsedTotality -= 1;
            if (classUsedTotality < 0) {
                return MapGenerator.getRes(520, "内部错误！");
            }
            cabinInfoFromDB.setBusinessClassUsedTotality(classUsedTotality);
        } else if (seatType == 2) {
            Integer classUsedTotality = cabinInfoFromDB.getFirstClassUsedTotality();
            classUsedTotality -= 1;
            if (classUsedTotality < 0) {
                return MapGenerator.getRes(520, "内部错误！");
            }
            cabinInfoFromDB.setFirstClassUsedTotality(classUsedTotality);
        }
        if (cabinInfoDao.updateByPrimaryKeySelective(cabinInfoFromDB) <= 0) {
            return MapGenerator.getRes(520, "内部错误！");
        }

        //订单状态设为-1(用户取消)，不删除
        mOrderFromDB.setOrderState(-1);
        if (mOrderDao.updateByPrimaryKeySelective(mOrderFromDB) > 0) {
            return MapGenerator.getRes(200, "取消订单成功！");
        }
        return MapGenerator.getRes(520, "内部错误！");
    }

    @Override
    public Map<String, Object> autoCancelOrder(MOrder mOrder) {
        MOrder mOrderFromDB = selectOrderById(mOrder.getOrderId());
        if (mOrderFromDB == null) {
            return MapGenerator.getRes(500, "订单不存在！");
        }
        if (!mOrder.getCustomerId().equals(mOrderFromDB.getCustomerId())) {
            return MapGenerator.getRes(501, "无权限取消！");
        }
        if (mOrderFromDB.getOrderState() != 0) {
            return MapGenerator.getRes(502, "订单状态不为待支付，不能取消！");
        }

        //修改已使用舱位数量
        CabinInfo cabinInfoFromDB = cabinInfoService.selectCabinInfoByFlightId(mOrderFromDB.getFlightId());
        Integer seatType = mOrderFromDB.getSeatType();
        if (seatType == 0) {
            Integer classUsedTotality = cabinInfoFromDB.getEconomyClassUsedTotality();
            classUsedTotality -= 1;
            if (classUsedTotality < 0) {
                return MapGenerator.getRes(520, "内部错误！");
            }
            cabinInfoFromDB.setEconomyClassUsedTotality(classUsedTotality);
        } else if (seatType == 1) {
            Integer classUsedTotality = cabinInfoFromDB.getBusinessClassUsedTotality();
            classUsedTotality -= 1;
            if (classUsedTotality < 0) {
                return MapGenerator.getRes(520, "内部错误！");
            }
            cabinInfoFromDB.setBusinessClassUsedTotality(classUsedTotality);
        } else if (seatType == 2) {
            Integer classUsedTotality = cabinInfoFromDB.getFirstClassUsedTotality();
            classUsedTotality -= 1;
            if (classUsedTotality < 0) {
                return MapGenerator.getRes(520, "内部错误！");
            }
            cabinInfoFromDB.setFirstClassUsedTotality(classUsedTotality);
        }
        if (cabinInfoDao.updateByPrimaryKeySelective(cabinInfoFromDB) <= 0) {
            return MapGenerator.getRes(520, "内部错误！");
        }

        //订单状态设为-4(超时取消)，不删除
        mOrderFromDB.setOrderState(-4);
        if (mOrderDao.updateByPrimaryKeySelective(mOrderFromDB) > 0) {
            return MapGenerator.getRes(200, "超时取消订单成功！");
        }
        return MapGenerator.getRes(520, "内部错误！");
    }

    @Override
    public Map<String, Object> freePay(MOrder mOrder) {
        MOrder mOrderFromDB = selectOrderById(mOrder.getOrderId());
        if (mOrderFromDB == null) {
            return MapGenerator.getRes(500, "订单不存在！");
        }
        if (!mOrder.getCustomerId().equals(mOrderFromDB.getCustomerId())) {
            return MapGenerator.getRes(501, "无权限支付！");
        }
        if (mOrderFromDB.getOrderState() != 0) {
            return MapGenerator.getRes(502, "订单状态不为待支付，不能支付！");
        }

        //订单状态设为1(已支付)
        mOrderFromDB.setOrderState(1);
        //支付方式设为3(余额支付)
        mOrderFromDB.setPaymentType(3);
        if (mOrderDao.updateByPrimaryKeySelective(mOrderFromDB) > 0) {
            return MapGenerator.getRes(200, "支付成功！");
        }
        return MapGenerator.getRes(520, "内部错误！");
    }

    @Override
    public Map<String, Object> freeRefund(MOrder mOrder) {
        MOrder mOrderFromDB = selectOrderById(mOrder.getOrderId());
        if (mOrderFromDB == null) {
            return MapGenerator.getRes(500, "订单不存在！");
        }
        if (!mOrder.getCustomerId().equals(mOrderFromDB.getCustomerId())) {
            return MapGenerator.getRes(501, "无权限退票！");
        }
        if (mOrderFromDB.getOrderState() != 1) {
            if (mOrderFromDB.getOrderState() == 2) {
                return MapGenerator.getRes(503, "已选座，不能退票，请取消选座后重试！");
            }
            if (mOrderFromDB.getOrderState() == 3) {
                return MapGenerator.getRes(504, "已出票，不能退票！");
            }
            return MapGenerator.getRes(502, "订单状态不为已支付/未选座，不能退票！");
        }

        Date nowDate = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(nowDate);
        calendar.add(Calendar.HOUR, 1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sDateStr = sdf.format(calendar.getTime());
        try {
            Date sDate = sdf.parse(sDateStr);
            if (sDate.after(mOrderFromDB.getLeaveTime())) {
                return MapGenerator.getRes(512, "手动退款时间截止到起飞前一小时，已超时，请去机场人工办理手续！");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //订单状态设为-2(用户退票)
        mOrderFromDB.setOrderState(-2);
        if (mOrderDao.updateByPrimaryKeySelective(mOrderFromDB) > 0) {
            return MapGenerator.getRes(200, "退票成功！");
        }
        return MapGenerator.getRes(520, "内部错误！");
    }

    @Override
    public Map<String, Object> returnPay(MOrder mOrder) {
        MOrder mOrderFromDB = selectOrderByNumber(mOrder.getOrderNumber());
        if (mOrderFromDB == null) {
            return MapGenerator.getRes(520, "内部错误！");
        }
        if (mOrderFromDB.getOrderState() != 0) {
            return MapGenerator.getRes(520, "内部错误！");
        }
        //订单状态设为1(已支付)
        mOrderFromDB.setOrderState(1);
        //支付方式设为1(支付宝)
        mOrderFromDB.setPaymentType(1);
        if (mOrderDao.updateByPrimaryKeySelective(mOrderFromDB) > 0) {
            return MapGenerator.getResWithData(200, "返回支付结果成功！", mOrderFromDB);
        }
        return MapGenerator.getRes(520, "内部错误！");
    }

    @Override
    public Map<String, Object> findOrdersByStates(List<Integer> stateList, String sort, boolean isASC, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<MOrder> orderList = selectOrdersByStates(stateList, orderSort(sort, isASC));
        PageInfo pageInfo = new PageInfo(orderList);
        if (!orderList.isEmpty()) {
            List<OrderVO> orderVOList = BeanUtil.copyList(orderList, OrderVO.class);
            pageInfo.setList(orderVOList);
            return MapGenerator.getResWithData(200, "获取订单列表成功！", pageInfo);
        } else {
            return MapGenerator.getRes(201, "获取结果为空！");
        }
    }

    @Override
    public Map<String, Object> findOrdersByIDNumberAndStates(String IDNumber, List<Integer> stateList, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<MOrder> orderList = selectOrdersByIDNumberAndStates(IDNumber, stateList);
        PageInfo pageInfo = new PageInfo(orderList);
        if (!orderList.isEmpty()) {
            List<OrderVO> orderVOList = BeanUtil.copyList(orderList, OrderVO.class);
            pageInfo.setList(orderVOList);
            return MapGenerator.getResWithData(200, "获取订单列表成功！", pageInfo);
        } else {
            return MapGenerator.getRes(201, "获取结果为空！");
        }
    }

    @Override
    public Map<String, Object> getCount() {
        MOrderExample mOrderExample = new MOrderExample();
        mOrderExample.or().andIsDeletedEqualTo(0);
        Long orderCount = mOrderDao.countByExample(mOrderExample);

        FlightExample flightExample = new FlightExample();
        flightExample.or().andIsDeletedEqualTo(0);
        Long flightCount = flightDao.countByExample(flightExample);

        CustomerExample customerExample = new CustomerExample();
        Long customerCount = customerDao.countByExample(customerExample);

        Map<String, Object> data = new HashMap<>();
        data.put("orderCount", orderCount);
        data.put("flightCount", flightCount);
        data.put("customerCount", customerCount);

        return MapGenerator.getResWithData(200, "获取统计数据成功！", data);
    }

    @Override
    public Map<String, Object> modifyOrder(MOrder mOrder) {
        MOrder mOrderFromDB = selectOrderById(mOrder.getOrderId());
        if (mOrderFromDB == null) {
            return MapGenerator.getRes(502, "订单不存在！");
        }
        //把参数信息项中的非空字段合并到来自数据库的信息项中
        BeanUtil.copyOneIgnoreNull(mOrder, mOrderFromDB);
        //覆盖更新日期
        mOrderFromDB.setUpdateTime(null);
        if (mOrderDao.updateByPrimaryKeySelective(mOrderFromDB) > 0) {
            return MapGenerator.getResWithData(200, "修改订单信息成功！", mOrderFromDB);
        }
        return MapGenerator.getRes(520, "内部错误！");
    }

    @Override
    public Map<String, Object> printTicket(Long orderId) {
        MOrder mOrderFromDB = selectOrderById(orderId);
        if (mOrderFromDB == null) {
            return MapGenerator.getRes(501, "订单不存在！");
        }
        if (mOrderFromDB.getOrderState() != 2) {
            return MapGenerator.getRes(502, "订单状态不为已选座，不能出票！");
        }
        //覆盖更新日期
        mOrderFromDB.setUpdateTime(null);
        mOrderFromDB.setOrderState(3);
        if (mOrderDao.updateByPrimaryKeySelective(mOrderFromDB) > 0) {
            //用户获得获得与实际消费金额等职的积分
            Customer userFromDB = userService.selectCustomerById(mOrderFromDB.getCustomerId());
            userFromDB.setScore(userFromDB.getScore() + mOrderFromDB.getPrice().intValue());
            return MapGenerator.getResWithData(200, "出票成功！", mOrderFromDB);
        }
        return MapGenerator.getRes(520, "内部错误！");
    }

    @Override
    public Map<String, Object> applyRefund(MOrder mOrder) {
        MOrder mOrderFromDB = selectOrderById(mOrder.getOrderId());
        if (mOrderFromDB == null) {
            return MapGenerator.getRes(500, "订单不存在！");
        }
        if (!mOrder.getCustomerId().equals(mOrderFromDB.getCustomerId())) {
            return MapGenerator.getRes(501, "无权限退票！");
        }
        if (mOrderFromDB.getOrderState() <= 0) {
            return MapGenerator.getRes(502, "此订单状态不支持申请退票！");
        }

        //订单状态设为-5(用户申请退票)
        mOrderFromDB.setOrderState(-5);
        if (mOrderDao.updateByPrimaryKeySelective(mOrderFromDB) > 0) {
            return MapGenerator.getRes(200, "申请退票成功，请耐心等待！");
        }
        return MapGenerator.getRes(520, "内部错误！");
    }

    //计算订单折扣后价格
    private BigDecimal calculatePrice(BigDecimal originalPrice, Discount discount, Integer discountType1, Integer
            discountType2) {
        BigDecimal price = new BigDecimal(0);
        BigDecimal discount1 = new BigDecimal(1);
        BigDecimal discount2 = new BigDecimal(1);

        if (discountType1 == 0) {
            discount1 = discount.getAdultDiscount();
        } else if (discountType1 == 1) {
            discount1 = discount.getChildrenDiscount();
        }

        if (discountType2 == 0) {
            discount2 = discount.getNormalDiscount();
        } else if (discountType2 == 1) {
            discount2 = discount.getSilverDiscount();
        } else if (discountType2 == 2) {
            discount2 = discount.getGoldDiscount();
        }

        if (discount1.doubleValue() <= 1) {
            price = originalPrice.multiply(discount1);
        } else {
            price = originalPrice.subtract(discount1);
        }

        if (discount2.doubleValue() <= 1) {
            price = price.multiply(discount2);
        } else {
            price = price.subtract(discount2);
        }
        return price;
    }

    //排序参数转化
    private MOrderExample orderSort(String sort, boolean isASC) {
        MOrderExample mOrderExample = new MOrderExample();
        sort = sort == null ? "" : sort;
        String column = "";
        String order = "desc";
        if (isASC) {
            order = "asc";
        }
        switch (sort) {
            case "orderId":
                column = "order_id";
                break;
            case "orderNumber":
                column = "order_number";
                break;
            case "flightId":
                column = "flight_id";
                break;
            case "flightNumber":
                column = "flight_number";
                break;
            case "leavePoint":
                column = "leave_point";
                break;
            case "arrivePoint":
                column = "arrive_point";
                break;
            case "leaveAirport":
                column = "leave_airport";
                break;
            case "arriveAirport":
                column = "arrive_airport";
                break;
            case "leaveTime":
                column = "leave_time";
                break;
            case "arriveTime":
                column = "arrive_time";
                break;
            case "flightDuration":
                column = "flight_duration";
                break;
            case "IDNumber":
                column = "ID_number";
                break;
            case "realname":
                column = "realname";
                break;
            case "phone":
                column = "phone";
                break;
            case "birthday":
                column = "birthday";
                break;
            case "contacts":
                column = "contacts";
                break;
            case "contactsPhone":
                column = "contacts_phone";
                break;
            case "companyId":
                column = "company_id";
                break;
            case "companyName":
                column = "company_name";
                break;
            case "planemodelId":
                column = "planemodel_id";
                break;
            case "planemodelName":
                column = "planemodel_name";
                break;
            case "seatId":
                column = "seat_id";
                break;
            case "seatType":
                column = "seat_type";
                break;
            case "seatNumber":
                column = "seat_number";
                break;
            case "customerId":
                column = "customer_id";
                break;
            case "discountType1":
                column = "discount_type1";
                break;
            case "discountType2":
                column = "discount_type2";
                break;
            case "originalPrice":
                column = "original_price";
                break;
            case "price":
                column = "price";
                break;
            case "paymentType":
                column = "payment_type";
                break;
            case "orderState":
                column = "order_state";
                break;
            case "createTime":
                column = "create_time";
                break;
            case "updateTime":
                column = "update_time";
                break;
            case "isDeleted":
                column = "is_deleted";
                break;
            default:
        }
        if ("".equals(column)) {
            mOrderExample.setOrderByClause("order_id desc");
        } else {
            if ("order_id".equals(column)) {
                mOrderExample.setOrderByClause(String.format("%s %s", column, order));
            } else {
                mOrderExample.setOrderByClause(String.format("%s %s , order_id desc", column, order));
            }
        }
        return mOrderExample;
    }
}
